﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using UnityEngine;

public class FileWriteAsync
{

	struct FileData {
		public string fileName;
		public string content;
		public bool isAppend;
		public string dir;
		public FileData(string dir,string fileName, string content, bool isAppend)
		{
			this.dir = dir;
			this.fileName = fileName;
			this.content = content;
			this.isAppend = isAppend;
		}
	}
	private static List<FileData> dataList = new List<FileData>();
	private static Thread thread = null;
	private static List<FileData> dataAsyncList = new List<FileData>();
	private static object locker = new object();
	public static void Write(string dir,string fileName,string content,bool isAppend = true)
	{
		lock (locker)
		{
			dataList.Add(new FileData(dir, fileName, content, isAppend));
			if (thread == null)
			{
				thread = new Thread(WriteAsync);
				thread.Start();
			}
		}
	}
	private static void WriteAsync() {
		while (true)
		{
			lock (locker)
			{
				dataAsyncList.Clear();
				foreach (var d in dataList)
				{
					dataAsyncList.Add(d);
				}
				dataList.Clear();
			}
			string dataPath = "";  //数据目录
			StreamWriter sw = null;
			string path = "";
			bool isAppend = false;
			try
			{
				foreach (var data in dataAsyncList)
				{
				
					if (path != data.fileName|| data.isAppend == false)
					{
						if (sw != null)
						{
							sw.Close();
							sw.Dispose();
							sw = null;
						}
						dataPath = data.dir + data.fileName;
						if (File.Exists(dataPath) && data.isAppend)
						{
							sw = new StreamWriter(dataPath, true);
						}
						else
						{
							if (!Directory.Exists(data.dir))
								Directory.CreateDirectory(data.dir);
							sw = new StreamWriter(dataPath, false);
						}
						isAppend = data.isAppend;
					}
					
					sw.WriteLine(data.content);
					path = data.fileName;
				}
				
			}
			catch
			{ }
			finally
			{
				if (sw != null)
				{
					sw.Close();
					sw.Dispose();
					sw = null;
				}

			}
			Thread.Sleep(33);
		}
		
	}
}
